#include <libbase/dswtcpserver_base.h>

CDswtcpserver_base::CDswtcpserver_base(LPST_ENV_T pEnv, int nPort)
: CDswbase(pEnv)
, m_pListener(NULL)
, m_nPort(nPort)
{
	CreateServer(nPort);
}

CDswtcpserver_base::~CDswtcpserver_base()
{
	if (m_pListener)
		evconnlistener_free(m_pListener);
}

void CDswtcpserver_base::OnAcceptError(struct evconnlistener *listener)
{
	struct event_base *base = evconnlistener_get_base(listener);
	int err = EVUTIL_SOCKET_ERROR();
	LOG4CPLUS_ERROR(log_dsw, "Got an error on the listener!err = " << evutil_socket_error_to_string(err));
}

void CDswtcpserver_base::CreateServer(int nPort)
{
	LOG4CPLUS_DEBUG(log_dsw, "Create tcp server on port " << nPort);
	struct sockaddr_in sin;
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = htonl(INADDR_ANY);
	sin.sin_port = htons(nPort);
	m_pListener = evconnlistener_new_bind(m_pEnv->pEvBase, CDswtcpserver_base::cb_OnAccept, this,
		LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE | LEV_OPT_THREADSAFE, -1, (struct sockaddr*)&sin, sizeof(sin));
	if (!m_pListener) {
		LOG4CPLUS_ERROR(log_dsw, "Couldn't create tcp server on port !" << nPort);
		return;
	}
	evconnlistener_set_error_cb(m_pListener, CDswtcpserver_base::cb_OnAcceptError);
}


